import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store/index.js'
import router from '@/router/index.js'
const request = axios.create({
  // baseURL: 'http://ihrm-java.itheima.net/api'
  baseURL: '/api'
})

request.interceptors.request.use(config => {
  // 在这个位置需要统一的去注入token
  if (store.state.user.token) {
    // 如果token存在 注入token
    config.headers.Authorization = 'Bearer ' + store.state.user.token
  }
  return config // 必须返回配置
}, error => {
  return Promise.reject(error)
})
request.interceptors.response.use(response => {
// Do something before response is sent
  // console.log('成功')
  // return response
  const { data: { success, data, message }} = response
  if (success) {
    return data
  } else {
    Message.error(message)
    throw new Error(message)
  }
}, error => {
  console.dir(error)
  if (error.response && error.response.status === 401) {
    Message.error('服务异常稍后重试')
    store.dispatch('user/logout')
    return router.push('/login')
  }
  // Do something with response error
  return Promise.reject(error)
})
export default request
